package com.fingard.util;

import org.springframework.util.Base64Utils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * AES工具类
 *
 * Created by cludy on 2020/08/07.
 */
public class AESUtil {

    private static final String KEY_ALGORITHM = "AES";
    /**
     * 默认的加密算法
     */
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

    /**
     * AES 加密操作
     *
     * @param content  待加密内容
     * @param password 加密密码(未转换为AES专用密钥)
     * @return 返回Base64转码后的加密数据
     */
    public static String encrypt(String content, String password) {
        SecretKeySpec secretKeySpec = getSecretKey(password, "UTF-8", 128);
        return encrypt(content, secretKeySpec, "UTF-8");
    }
    /**
     * AES 加密操作
     *
     * @param content  待加密内容
     * @param password 加密密码(未转换为AES专用密钥)
     * @param charset 字符集(不传默认UTF-8)
     * @return 返回Base64转码后的加密数据
     */
    public static String encrypt(String content, String password, String charset) {
        SecretKeySpec secretKeySpec = getSecretKey(password, charset, 128);
        return encrypt(content, secretKeySpec, charset);
    }
    /**
     * AES 加密操作
     *
     * @param content  待加密内容
     * @param password 加密密码(未转换为AES专用密钥)
     * @param charset 字符集(不传默认UTF-8)
     * @param secretKeyLength 密钥长度(不传默认128)
     * @return 返回Base64转码后的加密数据
     */
    public static String encrypt(String content, String password, String charset, int secretKeyLength) {
        SecretKeySpec secretKeySpec = getSecretKey(password, charset, secretKeyLength);
        return encrypt(content, secretKeySpec, charset);
    }
    /**
     * AES 加密操作
     *
     * @param content  待加密内容
     * @param secretKey AES专用密钥
     * @return 返回Base64转码后的加密数据
     */
    public static String encrypt(String content, SecretKeySpec secretKey, String charset) {
        try {
            // 创建密码器
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            byte[] byteContent = content.getBytes(charset);
            // 初始化为加密模式的密码器
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            // 加密
            byte[] result = cipher.doFinal(byteContent);
            //通过Base64转码返回
            return Base64Utils.encodeToString(result);
        } catch (Exception ex) {
        }
        return null;
    }
    /**
     * AES 解密操作
     *
     * @param content  待解密内容
     * @param password 解密密码(未转换为AES专用密钥)
     * @return
     */
    public static String decrypt(String content, String password) {
        SecretKeySpec secretKeySpec = getSecretKey(password, "UTF-8", 128);
        return decrypt(content, secretKeySpec,"UTF-8");
    }
    /**
     * AES 解密操作
     *
     * @param content  待解密内容
     * @param password 解密密码(未转换为AES专用密钥)
     * @param charset 字符集
     * @return
     */
    public static String decrypt(String content, String password, String charset) {
        SecretKeySpec secretKeySpec = getSecretKey(password, charset, 128);
        return decrypt(content, secretKeySpec, charset);
    }
    /**
     * AES 解密操作
     *
     * @param content  待解密内容
     * @param password 解密密码(未转换为AES专用密钥)
     * @param charset 字符集(不传默认UTF-8)
     * @param secretKeyLength 密钥长度(不传默认128)
     * @return
     */
    public static String decrypt(String content, String password, String charset, int secretKeyLength) {
        SecretKeySpec secretKeySpec = getSecretKey(password, charset, secretKeyLength);
        return decrypt(content, secretKeySpec, charset);
    }
    /**
     * AES 解密操作
     *
     * @param content  待解密内容
     * @param secretKey AES专用密钥
     * @param charset 字符集(不传默认UTF-8)
     * @return
     */
    public static String decrypt(String content, SecretKeySpec secretKey, String charset) {

        try {
            //实例化
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            //使用密钥初始化，设置为解密模式
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            //执行操作
            byte[] result = cipher.doFinal(Base64Utils.decodeFromString(content));
            String s = new String(result, charset);
            return s;
        } catch (Exception ex) {
        }

        return null;
    }
    /**
     * 生成加密秘钥
     * @param password 加密密码(未转换为AES专用密钥)
     * @return
     */
    private static SecretKeySpec getSecretKey(String password) {
        return getSecretKey(password, "UTF-8");
    }

    /**
     * 生成加密秘钥
     * @param password 加密密码(未转换为AES专用密钥)
     * @param charset 字符集
     * @return
     */
    private static SecretKeySpec getSecretKey(String password, String charset) {
        return getSecretKey(password, charset,128);
    }

    /**
     * 生成加密秘钥
     * @param password 加密密码(未转换为AES专用密钥)
     * @param secretKeyLength 密钥长度
     * @return
     */
    private static SecretKeySpec getSecretKey(String password, int secretKeyLength) {
        return getSecretKey(password, "UTF-8", secretKeyLength);
    }
    /**
     * 生成加密秘钥
     * @param password 加密密码(未转换为AES专用密钥)
     * @param charset 字符集
     * @param secretKeyLength 密钥长度
     * @return
     */
    private static SecretKeySpec getSecretKey(String password, String charset, int secretKeyLength) {
        //返回生成指定算法密钥生成器的 KeyGenerator 对象
        KeyGenerator kg = null;
        try {
            kg = KeyGenerator.getInstance(KEY_ALGORITHM);
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(password.getBytes(charset));
            //AES 要求密钥长度为 128
            kg.init(secretKeyLength, random);
            //生成一个密钥
            SecretKey secretKey = kg.generateKey();
            // 转换为AES专用密钥
            return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
        }
        return null;
    }


    /**
     * 获取MD5签名
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static String MD5Sign(String data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(data.getBytes(StandardCharsets.UTF_8));
        return Base64Utils.encodeToString(md.digest());
    }

    public static void main(String[] args) throws Exception {
        String tmpStr = "Hello Word!你好啊";
        String tmpPwd = "112233啊";
        System.out.println("encrypt:"+encrypt(tmpStr, tmpPwd));
        System.out.println("decrypt:"+decrypt("Dc3BaV0/bjDaQer5MgB7MsK+fTUM5N42UQDxLWk18Zc=", tmpPwd));
        System.out.println("encrypt2:"+encrypt(tmpStr, tmpPwd, "GBK"));
        System.out.println("decrypt2:"+decrypt("LHuc/toJc9eSM/CHebhx+KDwn+6vyBQwNB0KIB+Z4c8=", tmpPwd, "GBK"));
        System.out.println("encrypt3:"+encrypt(tmpStr, tmpPwd,"GBK", 256));
        System.out.println("decrypt3:"+decrypt("fO9BqfLXwizZ7EQhSnLSORIb6wz/5hlXaPt0nbXpRnw=", tmpPwd, "GBK",256));
    }

}

